package com.example.dynamicschedule.task;


import com.alibaba.fastjson.JSON;
import com.example.dynamicschedule.bean.*;
import com.example.dynamicschedule.config.ScanningCleaningConfig;
import com.example.dynamicschedule.dao.*;
import com.example.dynamicschedule.redis.RedisService;
import com.example.dynamicschedule.service.*;
import com.example.dynamicschedule.utils.BaseInformationUtils;
import com.example.dynamicschedule.utils.HttpClientUtils;
import com.example.dynamicschedule.utils.JSONUtils;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.*;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 清洗定时任务
 */

@Repository
public class ScanningCleaningDataTask {
    @Autowired
    private CkOrderLoanLoadService ckOrderLoanLoadService;
    @Autowired
    private CkOrderLoanIntelligenceDivisionService ckOrderLoanIntelligenceDivisionService;
    @Autowired
    private CkStopNoticePersonService ckStopNoticePersonService;
    @Autowired
    private ScanningCleaningConfig scanningCleaningConfig;
    @Autowired
    private CreditDataDownloadNewFormService creditDataDownloadNewFormService;
    @Autowired
    private CreditDataDownloadOldFormService creditDataDownloadOldFormService;
    @Autowired
    private CkOrderLoanOutsourcingService ckOrderLoanOutsourcingService;
    @Autowired
    private CkLevelMapper ckLevelMapper;
    @Autowired
    private CkOrderOutboundRecoveryLogMapper ckOrderOutboundRecoveryLogMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private CkFeedbackTableMapper ckFeedbackTableMapper;
    @Autowired
    private CkOrderRecoveryDataMapper ckOrderRecoveryDataMapper;
    @Autowired
    private CkOrderRecoveryDataService ckOrderRecoveryDataService;
    @Autowired
    private CkOrderAchievementFormService ckOrderAchievementFormService;
    @Autowired
    private CkOrderLoanPeopleDivisionMapper ckOrderLoanPeopleDivisionMapper;
    @Autowired
    private CkOrderLoanDivisionTimesMapper ckOrderLoanDivisionTimesMapper;
    @Autowired
    private UploadFileTask uploadFileTask;
    @Autowired
    private BaseInformationUtils baseInformationUtils;
   /* @Autowired
    private InsertLog insertLog;*/
    static Logger log = Logger.getLogger(ScanningCleaningDataTask.class);


    /**
     * 清晰规则定时器
     *
     * @throws Exception
     */
    @Transactional
    public void ScanningCleaningDataTask() throws Exception {
        Date date = new Date();
        log.info("规则清洗任务开始");
        log.info("扫描开始");

        boolean n = false;
        boolean o = false;
        List<CreditDataDownloadNewForm> creditDataDownloadNewForms = creditDataDownloadNewFormService.selectList(); //新表
        List<CreditDataDownloadOldForm> creditDataDownloadOldForms = creditDataDownloadOldFormService.selectList(); //旧表
        if (!CollectionUtils.isEmpty(creditDataDownloadNewForms)) {
            n = true;
        }
        if (!CollectionUtils.isEmpty(creditDataDownloadOldForms)) {
            o = true;
        }
        //LOG表
        List<CkOrderLoanLoad> nCkOrderLoanLoads = null;
        //智能催收的数据表
        Map<String, List<CkOrderLoanIntelligenceDivision>> ckOrderLoanIntelligenceDivisionMap = new HashMap<>();
        //失联停催表
        List<CkStopNoticePerson> ckStopNoticePeoples = new ArrayList<>();
        //风险表(码表)
        Map<String, List<CkLevel>> ckLevelMap = new HashMap<>();
        if (n || o) {
            //停催失联表
            ckStopNoticePeoples.addAll(ckStopNoticePersonService.selectByType((byte) 1));
            ckStopNoticePeoples.addAll(ckStopNoticePersonService.selectByType((byte) 2));
            //逾期等级
            List<CkLevel> dayList = ckLevelMapper.findByCategory((byte) 1);
            ckLevelMap.put("day", dayList);
            //评分风险等级
            List<CkLevel> scoreList = ckLevelMapper.findByCategory((byte) 3);
            ckLevelMap.put("score", scoreList);
        }
        //智能分案总表
        Map<String, List<CkOrderLoanIntelligenceDivision>> ckOrderLoanIntelligenceDivisionAllMap = new HashMap<>();
        if (n) {
            //新下拉表处理
            ckOrderLoanIntelligenceDivisionAllMap = nTableCaseProcessing(nCkOrderLoanLoads, creditDataDownloadNewForms,
                    ckStopNoticePeoples, ckOrderLoanIntelligenceDivisionMap, ckLevelMap, ckOrderLoanIntelligenceDivisionAllMap);
        }
        if (o) {
            //旧下拉处理
            ckOrderLoanIntelligenceDivisionAllMap = oTableCaseProcessing(nCkOrderLoanLoads, creditDataDownloadOldForms,
                    ckStopNoticePeoples, ckOrderLoanIntelligenceDivisionMap, ckLevelMap, ckOrderLoanIntelligenceDivisionAllMap);
            log.info("删除下载旧表数据库内容开始");
            creditDataDownloadOldFormService.deleteList(creditDataDownloadOldForms);
            log.info("删除下载旧表数据库内容结束");
        }

           /* //委外人工分案处理
            ckOrderLoanIntelligenceDivisionAllList= addOutsourcingPeople(ckOrderLoanIntelligenceDivisionAllList);*/
            /*//再次人工分案处理处理
            ckOrderLoanIntelligenceDivisionAllList=  peopleReDivision(ckOrderLoanIntelligenceDivisionAllList);*/
        List<CkOrderLoanIntelligenceDivision> ckOrderLoanIntelligenceDivisionAllList = ckOrderLoanIntelligenceDivisionAllMap.get("all");
        if (!CollectionUtils.isEmpty(ckOrderLoanIntelligenceDivisionAllList)) {
            log.info("清洗开始");
            Map<String, Map<String, List<CkOrderLoanIntelligenceDivision>>> handleMap = getHandleMap(ckOrderLoanIntelligenceDivisionAllList);
            log.info("清洗结束");
            log.info("外呼和短信一起发送处理短信开始");
            handleMap = parallelMessage(handleMap, ckOrderLoanIntelligenceDivisionAllMap);
            log.info("外呼和短信一起发送处理短信结束");
            log.info("下发渠道次数记录开始");
            divisionChannel(handleMap);
            log.info("下发渠道次数记录结束");
            //人工外呼文件生成
            peopleFileGeneration(handleMap);
            //智能外呼文件生成
            intelligenceFileGeneration(handleMap);
            //短信文件生成
            messageFileGeneration(handleMap, ckOrderLoanIntelligenceDivisionAllMap);
            handleMap.clear();
            ckOrderLoanIntelligenceDivisionAllMap.clear();
        } else {
            log.info("没有当天数据");
        }
        log.info("下发三方任务开始");
        uploadFileTask.UploadFileTask();
        log.info("下发三方任务结束");
    }

    /**
     * 对于old表进行清洗  清洗规则为:未拨打数据继续下发 已拨打数据当在7 14 21 28 加30天的情况下继续下发
     *
     * @param creditDataDownloadOldForms
     * @return
     */
    private List<CkOrderLoanLoad> cleanOldCreditDataDownloadFormData(
            List<CkOrderLoanLoad> creditDataDownloadOldForms) {
        List<String> serialNumbers = new ArrayList<>();
        Map<String, CkOrderLoanLoad> creditDataDownloadOldFormMap = new HashMap<>();
        for (CkOrderLoanLoad creditDataDownloadOldForm : creditDataDownloadOldForms) {
            String serialNumber = creditDataDownloadOldForm.getSerialNumber();
            serialNumbers.add(serialNumber);
            creditDataDownloadOldFormMap.put(serialNumber, creditDataDownloadOldForm);
        }
        List<CkOrderLoanLoad> creditDataDownloadOldFormArrayList = new ArrayList<>();
        List<CkOrderLoanIntelligenceDivision> ckOrderLoanIntelligenceDivisions = ckOrderLoanIntelligenceDivisionService.selectBySerialNumbers(serialNumbers);
        for (CkOrderLoanIntelligenceDivision ckOrderLoanIntelligenceDivision : ckOrderLoanIntelligenceDivisions) {
            String serialNumber = ckOrderLoanIntelligenceDivision.getSerialNumber();
            CkOrderLoanLoad creditDataDownloadOldForm = creditDataDownloadOldFormMap.get(serialNumber);
            Integer isDialed = ckOrderLoanIntelligenceDivision.getIsDialed();
            if (isDialed == 2) {
                creditDataDownloadOldFormArrayList.add(creditDataDownloadOldForm);
            } else {
                Integer overdueDay = creditDataDownloadOldForm.getOverdueDay();
                boolean b = true;
                while (b) {
                    if (overdueDay - 30 < 0) {
                        b = false;
                    } else {
                        overdueDay = overdueDay - 30;
                    }
                }
                if (overdueDay == 7 || overdueDay == 14 || overdueDay == 21 || overdueDay == 28) {
                    creditDataDownloadOldFormArrayList.add(creditDataDownloadOldForm);
                }
            }
        }
        return creditDataDownloadOldFormArrayList;
    }

    /**
     * 并行处理短信
     *
     * @param handleMap
     * @param ckOrderLoanIntelligenceDivisionAllMap
     * @return
     */
    private Map<String, Map<String, List<CkOrderLoanIntelligenceDivision>>> parallelMessage(Map<String, Map<String, List<CkOrderLoanIntelligenceDivision>>> handleMap, Map<String, List<CkOrderLoanIntelligenceDivision>> ckOrderLoanIntelligenceDivisionAllMap) {
        if (!CollectionUtils.isEmpty(ckOrderLoanIntelligenceDivisionAllMap.get("message"))) {
            List<CkOrderLoanIntelligenceDivision> message = ckOrderLoanIntelligenceDivisionAllMap.get("message");
            Map<String, List<CkOrderLoanIntelligenceDivision>> messageMap = new HashMap<>();
            for (CkOrderLoanIntelligenceDivision ckOrderLoanIntelligenceDivision : message) {
                String peopleId = ckOrderLoanIntelligenceDivision.getPeopleId();
                List<CkOrderLoanIntelligenceDivision> ckOrderLoanIntelligenceDivisionList = null;
                if (CollectionUtils.isEmpty(messageMap.get(peopleId))) {
                    ckOrderLoanIntelligenceDivisionList = new ArrayList<>();
                } else {
                    ckOrderLoanIntelligenceDivisionList = messageMap.get(peopleId);
                }
                ckOrderLoanIntelligenceDivisionList.add(ckOrderLoanIntelligenceDivision);
                messageMap.put(peopleId, ckOrderLoanIntelligenceDivisionList);
            }
            if (handleMap.get("金信通") != null) {
                Map<String, List<CkOrderLoanIntelligenceDivision>> oMessageMap = handleMap.get("金信通");
                oMessageMap.putAll(messageMap);
            } else {
                handleMap.put("金信通", messageMap);
            }
        }
        return handleMap;
    }

    /**
     * 分案查询每一条的log
     *
     * @param handleMap
     */
    private void divisionChannel(Map<String, Map<String, List<CkOrderLoanIntelligenceDivision>>> handleMap) {
        Date date = new Date();
        Byte channel = null;
        List<CkOrderLoanDivisionTimes> ckOrderDivisionTimesList = new ArrayList<>();
        for (Map.Entry<String, Map<String, List<CkOrderLoanIntelligenceDivision>>> stringMapEntry : handleMap.entrySet()) {
            String key = stringMapEntry.getKey();
            Map<String, List<CkOrderLoanIntelligenceDivision>> value = stringMapEntry.getValue();
            if ("人工外呼".equalsIgnoreCase(key)) {
                channel = 3;
            } else if ("智能外呼".equalsIgnoreCase(key)) {
                channel = 2;
            } else if ("金信通".equalsIgnoreCase(key)) {
                channel = 1;
            }
            for (Map.Entry<String, List<CkOrderLoanIntelligenceDivision>> stringListEntry : value.entrySet()) {
                List<CkOrderLoanIntelligenceDivision> value1 = stringListEntry.getValue();
                for (CkOrderLoanIntelligenceDivision ckOrderLoanIntelligenceDivision : value1) {
                    String serialNumber = ckOrderLoanIntelligenceDivision.getSerialNumber();
                    Byte isFirstIssue = ckOrderLoanIntelligenceDivision.getIsFirstIssue();

                    CkOrderLoanDivisionTimes ckOrderDivisionTimes = new CkOrderLoanDivisionTimes();
                    BeanUtils.copyProperties(ckOrderLoanIntelligenceDivision, ckOrderDivisionTimes);
                    ckOrderDivisionTimes.setDataTime(date);
                    ckOrderDivisionTimes.setOutbound(channel);
                    ckOrderDivisionTimes.setDivision((byte) 2);
                    ckOrderDivisionTimes.setSerialNumber(serialNumber);
                    if (isFirstIssue == 0) {
                        ckOrderDivisionTimes.setIsFirstIssue(0);
                    } else if (isFirstIssue == 1) {
                        ckOrderDivisionTimes.setIsFirstIssue(1);
                    }
                    ckOrderDivisionTimes.setIsDelete((byte) 0);
                    ckOrderDivisionTimesList.add(ckOrderDivisionTimes);
                }
            }
        }
        log.info("存储下发次数开始");  //因sql最多缓存64M,故每30000提交一次
        if (!CollectionUtils.isEmpty(ckOrderDivisionTimesList)) {
            int size = ckOrderDivisionTimesList.size();
            if (size > 30000) {
                int s = size / 30000;
                for (int i = 1; i <= s; i++) {
                    int b = 30000 * i;
                    List<CkOrderLoanDivisionTimes> ckOrderLoanLoads = new ArrayList<>();
                    if (i == s) {
                        for (int j = 30000 * (i - 1); j < size; j++) {
                            ckOrderLoanLoads.add(ckOrderDivisionTimesList.get(j));
                        }
                    } else if (i == 1) {
                        for (int j = 0; j < b; j++) {
                            ckOrderLoanLoads.add(ckOrderDivisionTimesList.get(j));
                        }
                    } else {
                        for (int j = 30000 * (i - 1); j < b; j++) {
                            ckOrderLoanLoads.add(ckOrderDivisionTimesList.get(j));
                        }
                    }
                    ckOrderLoanDivisionTimesMapper.insertForEach(ckOrderLoanLoads);
                }
            } else {
                ckOrderLoanDivisionTimesMapper.insertForEach(ckOrderDivisionTimesList);
            }
        }
        log.info("存储下发次数结束");
    }

    /**
     * 再次分案
     *
     * @param ckOrderLoanIntelligenceDivisionAllList
     * @return
     */
    private List<CkOrderLoanIntelligenceDivision> peopleReDivision(List<CkOrderLoanIntelligenceDivision> ckOrderLoanIntelligenceDivisionAllList) {
        List<CkOrderLoanPeopleDivision> ckOrderLoanPeopleDivisions = ckOrderLoanPeopleDivisionMapper.selectByStatus((byte) 0);
        if (CollectionUtils.isEmpty(ckOrderLoanPeopleDivisions)) {
            return ckOrderLoanIntelligenceDivisionAllList;
        } else {
            Map<String, CkOrderLoanIntelligenceDivision> ckOrderLoanIntelligenceDivisionMap = new HashMap<>();
            for (CkOrderLoanIntelligenceDivision ckOrderLoanIntelligenceDivision : ckOrderLoanIntelligenceDivisionAllList) {
                String serialNumber = ckOrderLoanIntelligenceDivision.getSerialNumber();
                ckOrderLoanIntelligenceDivisionMap.put(serialNumber, ckOrderLoanIntelligenceDivision);
            }
            for (CkOrderLoanPeopleDivision ckOrderLoanPeopleDivision : ckOrderLoanPeopleDivisions) {
                String serialNumber = ckOrderLoanPeopleDivision.getSerialNumber();
                if (ckOrderLoanIntelligenceDivisionMap.get(serialNumber) != null) {
                    Byte aByte = ckOrderLoanPeopleDivision.getnOutbound();
                    CkOrderLoanIntelligenceDivision ckOrderLoanIntelligenceDivision = ckOrderLoanIntelligenceDivisionMap.get(serialNumber);
                    ckOrderLoanIntelligenceDivision.setOutbound(aByte);
                    ckOrderLoanIntelligenceDivisionMap.put(serialNumber, ckOrderLoanIntelligenceDivision);
                }
            }
            List<CkOrderLoanIntelligenceDivision> ckOrderLoanIntelligenceDivisions = new ArrayList<>();
            for (Map.Entry<String, CkOrderLoanIntelligenceDivision> stringCkOrderLoanIntelligenceDivisionEntry : ckOrderLoanIntelligenceDivisionMap.entrySet()) {
                CkOrderLoanIntelligenceDivision value = stringCkOrderLoanIntelligenceDivisionEntry.getValue();
                ckOrderLoanIntelligenceDivisions.add(value);
            }
            return ckOrderLoanIntelligenceDivisions;
        }
    }

    /**
     * 委外人工分案处理
     *
     * @param ckOrderLoanIntelligenceDivisionAllList
     * @return
     */
    private List<CkOrderLoanIntelligenceDivision> addOutsourcingPeople(List<CkOrderLoanIntelligenceDivision> ckOrderLoanIntelligenceDivisionAllList) {
        log.info("处理委外案列人工分案开始");
        List<CkOrderLoanOutsourcing> ckOrderLoanOutsourcings = ckOrderLoanOutsourcingService.findByStatus((byte) 1);
        if (CollectionUtils.isEmpty(ckOrderLoanOutsourcings)) {
            return ckOrderLoanIntelligenceDivisionAllList;
        } else {
            log.info("人工分案处理开始,参数为:" + JSON.toJSONString(ckOrderLoanOutsourcings));
            ckOrderLoanOutsourcings.stream().forEach(ckOrderLoanOutsourcing -> {
                Integer collectionTimes = ckOrderLoanOutsourcing.getCollectionTimes();
                if (collectionTimes != null) {
                    collectionTimes += 1;
                } else {
                    collectionTimes = 1;
                }
                ckOrderLoanOutsourcing.setCollectionTimes(collectionTimes);
                ckOrderLoanOutsourcing.setDivision((byte) 2);
                CkOrderLoanIntelligenceDivision ckOrderLoanIntelligenceDivision = new CkOrderLoanIntelligenceDivision();
                BeanUtils.copyProperties(ckOrderLoanOutsourcing, ckOrderLoanIntelligenceDivision);
                ckOrderLoanIntelligenceDivision.setOutbound((byte) 3);
                ckOrderLoanIntelligenceDivision.setOverdueGrade("M3");
                ckOrderLoanIntelligenceDivisionAllList.add(ckOrderLoanIntelligenceDivision);
            });
            log.info("人工分案处理结束");
            log.info("更新委外案列数据开始");
            if (!CollectionUtils.isEmpty(ckOrderLoanOutsourcings)) {
                ckOrderLoanOutsourcingService.updateForEach(ckOrderLoanOutsourcings);
            }
            log.info("更新委外案列数据结束");
            return ckOrderLoanIntelligenceDivisionAllList;
        }
    }

    /**
     * 委外筛选处理
     *
     * @param ckOrderLoanIntelligenceDivisionAllList
     */
    private List<CkOrderLoanIntelligenceDivision> outsourcing(List<CkOrderLoanIntelligenceDivision> ckOrderLoanIntelligenceDivisionAllList) {
        log.info("处理委外和outbound为0的数据开始");
        List<CkOrderLoanOutsourcing> ckOrderLoanOutsourcings = new ArrayList<>();
        Iterator<CkOrderLoanIntelligenceDivision> iterator = ckOrderLoanIntelligenceDivisionAllList.iterator();
        List<CkOrderLoanDivisionTimes> ckOrderLoanDivisionTimesList = new ArrayList<>();
        while (iterator.hasNext()) {
            CkOrderLoanIntelligenceDivision ckOrderLoanIntelligenceDivision = iterator.next();
            if (ckOrderLoanIntelligenceDivision.getOutbound() == 4) {
                CkOrderLoanOutsourcing ckOrderLoanOutsourcing = new CkOrderLoanOutsourcing();
                BeanUtils.copyProperties(ckOrderLoanIntelligenceDivision, ckOrderLoanOutsourcing);
                ckOrderLoanOutsourcings.add(ckOrderLoanOutsourcing);
                CkOrderLoanDivisionTimes ckOrderLoanDivisionTime = new CkOrderLoanDivisionTimes();
                BeanUtils.copyProperties(ckOrderLoanIntelligenceDivision, ckOrderLoanDivisionTime);
                ckOrderLoanDivisionTime.setDataTime(new Date());
                ckOrderLoanDivisionTimesList.add(ckOrderLoanDivisionTime);
                iterator.remove();
            } else if (ckOrderLoanIntelligenceDivision.getOutbound() == 0) {
                iterator.remove();
            }
        }
        if (!CollectionUtils.isEmpty(ckOrderLoanOutsourcings)) {
            ckOrderLoanOutsourcingService.insertList(ckOrderLoanOutsourcings);
        }
        if (!CollectionUtils.isEmpty(ckOrderLoanDivisionTimesList)) {
            ckOrderLoanDivisionTimesMapper.insertForEach(ckOrderLoanDivisionTimesList);
        }
        log.info("处理委外和outbound为0的数据结束");
        return ckOrderLoanIntelligenceDivisionAllList;
    }

    /**
     * 短信文件生成
     *
     * @param handleMap
     * @param ckOrderLoanIntelligenceDivisionAllMap
     * @throws Exception
     */
    private void messageFileGeneration(Map<String, Map<String, List<CkOrderLoanIntelligenceDivision>>> handleMap,
                                       Map<String, List<CkOrderLoanIntelligenceDivision>> ckOrderLoanIntelligenceDivisionAllMap) throws Exception {
        Date date = new Date();
        log.info("处理短信模板信息,生成.txt文件开始");
        Map<String, List<String>> informationTxt = getInformationTxt(handleMap);
        String txtPath = scanningCleaningConfig.getTxtUploadPath();
        File txtFile = new File(txtPath);
        if (!txtFile.exists()) {
            txtFile.mkdirs();
        }
        for (Map.Entry<String, List<String>> stringListEntry : informationTxt.entrySet()) {
            String fileName = stringListEntry.getKey();
            List<String> value = stringListEntry.getValue();
            if (!CollectionUtils.isEmpty(value)) {
                log.info("短信生成json文件开始,文件名:" + fileName);
                writeLineTxtFile(fileName, txtPath, value, ".txt");
                log.info("短信生成json文件结束");
            }

        }
        log.info("处理短信模板信息,生成.txt文件结束");
        log.info("由于短信无返回,设定返回状态为承诺回款开始");
        saveMessageRecoverResult(handleMap, ckOrderLoanIntelligenceDivisionAllMap);
        log.info("由于短信无返回,设定返回状态为承诺回款结束");
        log.info("存储金信通到log表开始");
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat1.format(date);
        CkOrderOutboundRecoveryLog ckOrderOutboundRecoveryLog = new CkOrderOutboundRecoveryLog();
        ckOrderOutboundRecoveryLog.setDataTime(format);
        ckOrderOutboundRecoveryLog.setOutboundType("金信通");
        ckOrderOutboundRecoveryLog.setStatus((byte) 1);

        ckOrderOutboundRecoveryLogMapper.insert(ckOrderOutboundRecoveryLog);
        log.info("存储金信通到log表结束");
    }

    /**
     * 智能外呼文件处理
     *
     * @param handleMap
     * @throws Exception
     */
    private void intelligenceFileGeneration(Map<String, Map<String, List<CkOrderLoanIntelligenceDivision>>> handleMap) throws Exception {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String dateStr = simpleDateFormat.format(date);
        log.info("智能外呼处理文件开始");
        Map<String, Map<String, List<CkOrderLoanIntelligenceDivision>>> intelligenceMap = new HashMap<>();

        if (handleMap.get("智能外呼") != null) {
            intelligenceMap.put("智能外呼", handleMap.get("智能外呼"));
        }
        String intelligenceJsonStr = JSON.toJSONString(intelligenceMap);
        File intelligenceJsonFile = new File(scanningCleaningConfig.getIntelligenceUploadJsonPath());
        if (!intelligenceJsonFile.exists()) {
            intelligenceJsonFile.mkdirs();
        }
        String intelligenceJsonPath = scanningCleaningConfig.getIntelligenceUploadJsonPath() + scanningCleaningConfig.getPrefixUploadJsonPath().replace("yyyyMMdd", dateStr);
        log.info("智能外呼生成json文件开始,文件名称为:" + intelligenceJsonPath);
        writeJsonFile(intelligenceJsonPath, intelligenceJsonStr);
        log.info("智能外呼处理成json格式结束");
        /*//存储操作log
        CkInsertLog ckInsertLog = new CkInsertLog();
        ckInsertLog.setLogId(UUID.randomUUID().toString());
        ckInsertLog.setOperationType("智能外呼保存OSS地址文件信息");
        ckInsertLog.setParams(JSON.toJSONString(intelligenceJsonPath));
        ckInsertLog.setTimes(new Date());
        insertLog.insertLog(ckInsertLog);*/
        String intelligenceOkPath = intelligenceJsonPath.replace("json", "ok");
        log.info("智能外呼生成ok文件开始,文件名称为:" + intelligenceJsonPath);
        writeJsonFile(intelligenceOkPath, intelligenceJsonStr);
        log.info("智能外呼处理成ok格式结束");
        log.info("智能外呼处理文件结束");
    }

    /**
     * 人工文件生成
     *
     * @param handleMap
     */
    private void peopleFileGeneration(Map<String, Map<String, List<CkOrderLoanIntelligenceDivision>>> handleMap) throws Exception {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String dateStr = simpleDateFormat.format(date);
        log.info("人工外呼生成文件开始");
        Map<String, Map<String, List<CkOrderLoanIntelligenceDivision>>> peopleMap = new HashMap<>();

        if (handleMap.get("人工外呼") != null) {
            peopleMap.put("人工外呼", handleMap.get("人工外呼"));
        }
        int count = 0;
        for (Map.Entry<String, Map<String, List<CkOrderLoanIntelligenceDivision>>> stringMapEntry : peopleMap.entrySet()) {
            Map<String, List<CkOrderLoanIntelligenceDivision>> value = stringMapEntry.getValue();
            for (Map.Entry<String, List<CkOrderLoanIntelligenceDivision>> stringListEntry : value.entrySet()) {
                List<CkOrderLoanIntelligenceDivision> value1 = stringListEntry.getValue();
                count += value1.size();
            }
        }
        String peopleJsonStr = JSON.toJSONString(peopleMap);
        File peopleJsonFile = new File(scanningCleaningConfig.getPeopleUploadJsonPath());
        if (!peopleJsonFile.exists()) {
            peopleJsonFile.mkdirs();
        }
        String peopleJsonPath = scanningCleaningConfig.getPeopleUploadJsonPath() + scanningCleaningConfig.getPrefixUploadJsonPath().replace("yyyyMMdd", dateStr);
        log.info("人工外呼生成json文件开始,文件名称为:" + peopleJsonPath);
        writeJsonFile(peopleJsonPath, peopleJsonStr);
        log.info("人工外呼处理成json格式结束");
        String peopleOkPath = peopleJsonPath.replace("json", "ok");
        log.info("人工外呼生成ok文件开始,文件名称为:" + peopleOkPath);
        writeJsonFile(peopleOkPath, peopleJsonStr);
        log.info("人工外呼处理成ok格式结束");
        log.info("人工外呼存储总条数到redis开始");
        Map<String, Object> redisMap = new HashMap<>();
        redisMap.put("EsbFilePath", scanningCleaningConfig.getPackageName() + "people/" + scanningCleaningConfig.getPrefixUploadJsonPath().replace("yyyyMMdd", dateStr));
        redisMap.put("EsbCount", count);
        redisService.hmset("EsbFilePathAndCount", redisMap);
      /*  //存储操作log
        CkInsertLog ckInsertLog = new CkInsertLog();
        ckInsertLog.setLogId(UUID.randomUUID().toString());
        ckInsertLog.setOperationType("人工外呼保存redis地址信息");
        ckInsertLog.setParams(JSON.toJSONString(redisMap));
        ckInsertLog.setTimes(new Date());
        insertLog.insertLog(ckInsertLog);*/
        log.info("人工外呼存储总条数到redis结束");
        log.info("人工外呼生成文件结束");
    }


    /**
     * @param nCkOrderLoanLoads                     log表数据
     * @param creditDataDownloadOldForms            旧表数据
     * @param ckStopNoticePeoples                   停催和失联表
     * @param ckOrderLoanIntelligenceDivisionMap
     * @param ckLevelMap
     * @param ckOrderLoanIntelligenceDivisionAllMap
     * @return
     * @throws Exception
     */
    private Map<String, List<CkOrderLoanIntelligenceDivision>> oTableCaseProcessing(List<CkOrderLoanLoad> nCkOrderLoanLoads,
                                                                                    List<CreditDataDownloadOldForm> creditDataDownloadOldForms,
                                                                                    List<CkStopNoticePerson> ckStopNoticePeoples,
                                                                                    Map<String, List<CkOrderLoanIntelligenceDivision>> ckOrderLoanIntelligenceDivisionMap,
                                                                                    Map<String, List<CkLevel>> ckLevelMap,
                                                                                    Map<String, List<CkOrderLoanIntelligenceDivision>> ckOrderLoanIntelligenceDivisionAllMap) throws Exception {

        if (!CollectionUtils.isEmpty(creditDataDownloadOldForms)) {
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
            SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyy-MM-dd");
            String dateStr = simpleDateFormat.format(date);
            nCkOrderLoanLoads = new ArrayList<>();
            log.info("执行旧文件存储清洗工作");
            Map<String, CreditDataDownloadOldForm> creditDataDownloadOldFormMap = new HashMap<>();
            List<CkOrderLoanLoad> finalNCkOrderLoanLoads = nCkOrderLoanLoads;
            creditDataDownloadOldForms.stream().forEach(creditDataDownloadOldForm -> {
                CkOrderLoanLoad ckOrderLoanLoad = new CkOrderLoanLoad();
                BeanUtils.copyProperties(creditDataDownloadOldForm, ckOrderLoanLoad);
                ckOrderLoanLoad.setDataTime(yyyyMMdd.format(date));
                finalNCkOrderLoanLoads.add(ckOrderLoanLoad);
                String serialNumber = creditDataDownloadOldForm.getSerialNumber();
                creditDataDownloadOldFormMap.put(serialNumber, creditDataDownloadOldForm);
                ckOrderLoanLoad = null;
            });
            if (!CollectionUtils.isEmpty(nCkOrderLoanLoads)) {
                //因sql最多缓存64M,故每30000提交一次
                int size = nCkOrderLoanLoads.size();
                if (size > 30000) {
                    int s = size / 30000;
                    for (int i = 1; i <= s; i++) {
                        int b = 30000 * i;
                        List<CkOrderLoanLoad> ckOrderLoanLoads = new ArrayList<>();
                        if (i == s) {
                            for (int j = 30000 * (i - 1); j < size; j++) {
                                ckOrderLoanLoads.add(nCkOrderLoanLoads.get(j));
                            }
                        } else if (i == 1) {
                            for (int j = 0; j < b; j++) {
                                ckOrderLoanLoads.add(nCkOrderLoanLoads.get(j));
                            }
                        } else {
                            for (int j = 30000 * (i - 1); j < b; j++) {
                                ckOrderLoanLoads.add(nCkOrderLoanLoads.get(j));
                            }
                        }
                        ckOrderLoanLoadService.insertForeach(ckOrderLoanLoads);
                    }
                } else {
                    ckOrderLoanLoadService.insertForeach(nCkOrderLoanLoads);
                }
            }
            log.info("旧表插入大数据信息表(信贷)成功");
            log.info("旧表筛选回款核销开始");
            //已回款或者已核销或者已删除
            List<CkOrderLoanLoad> paymentList = new ArrayList<>();
            //未回款
            List<CkOrderLoanLoad> noPaymentList = new ArrayList<>();
            for (CkOrderLoanLoad nCkOrderLoanLoad : nCkOrderLoanLoads) {
                Byte state = nCkOrderLoanLoad.getState();
                Byte isDelete = nCkOrderLoanLoad.getIsDelete();
                if (isDelete != null) {
                    if (isDelete == 1) {
                        paymentList.add(nCkOrderLoanLoad);
                        continue;
                    }
                }
                if (state != null) {
                    if (state == 2 || state == 1) {
                        if (state == 2) {
                            Double overdueAmount = nCkOrderLoanLoad.getOverdueAmount();
                            Double repaymentAmount = nCkOrderLoanLoad.getRepaymentAmount();
                            if (overdueAmount <= repaymentAmount) {
                                paymentList.add(nCkOrderLoanLoad);
                            } else {
                                nCkOrderLoanLoad.setState((byte) 0);
                                noPaymentList.add(nCkOrderLoanLoad);
                            }
                        } else if (state == 1) {
                            paymentList.add(nCkOrderLoanLoad);
                        }
                    } else {
                        noPaymentList.add(nCkOrderLoanLoad);
                    }
                }

            }
            nCkOrderLoanLoads.clear();
            log.info("旧表筛选回款核销结束");
            log.info("旧表已回款处理开始");
           /* log.info("已回款催收员成绩表开始");
            saveCollector(paymentList);
            log.info("已回款催收员成绩表结束");*/
            //回款数据
            List<CkOrderLoanIntelligenceDivision> oldCkOrderLoanIntelligenceDivisions = new ArrayList<>();
            List<CkOrderLoanLoad> mergeSerialNumbers = new ArrayList<>();
            for (CkOrderLoanLoad ckOrderLoanLoad : paymentList) {
                if (ckOrderLoanLoad.getIsDelete() == 1) {
                    mergeSerialNumbers.add(ckOrderLoanLoad);
                }
                CkOrderLoanIntelligenceDivision ckOrderLoanIntelligenceDivision = new CkOrderLoanIntelligenceDivision();
                BeanUtils.copyProperties(ckOrderLoanLoad, ckOrderLoanIntelligenceDivision);
                ckOrderLoanIntelligenceDivision.setIsDialed(1);
                Calendar instance = Calendar.getInstance();
                instance.setTime(date);
                instance.add(Calendar.DATE, -1);
                Date time = instance.getTime();
                String format = yyyyMMdd.format(time);
                ckOrderLoanIntelligenceDivision.setDataTime(format);
                oldCkOrderLoanIntelligenceDivisions.add(ckOrderLoanIntelligenceDivision);
                //删除大数据回收的回款数据
                String serialNumber = ckOrderLoanLoad.getSerialNumber();
                creditDataDownloadOldFormMap.remove(serialNumber);
            }

            // 根据案件号更新
            if (!CollectionUtils.isEmpty(oldCkOrderLoanIntelligenceDivisions)) {
                ckOrderLoanIntelligenceDivisionService.updateForEach(oldCkOrderLoanIntelligenceDivisions);
            }
            log.info("旧表已回款处理结束");
           /* if (!CollectionUtils.isEmpty(mergeSerialNumbers)) {
                log.info("旧表更新反馈为已合并开始");
                String mergeStr = ckFeedbackTableMapper.selectByChinese("已合并");
                List<CkOrderRecoveryData> ckOrderRecoveryDataArrayList = new ArrayList<>();
                //List<CkOrderLoanDivisionTimes> ckOrderLoanDivisionTimesList = new ArrayList<>();
                for (CkOrderLoanLoad mergeSerialNumber : mergeSerialNumbers) {
                    CkOrderRecoveryData ckOrderRecoveryData = new CkOrderRecoveryData();
                    BeanUtils.copyProperties(mergeSerialNumber, ckOrderRecoveryData);
                    ckOrderRecoveryData.setFeedbackCode(mergeStr);
                    ckOrderRecoveryDataArrayList.add(ckOrderRecoveryData);
                   *//* CkOrderLoanDivisionTimes ckOrderLoanDivisionTimes = new CkOrderLoanDivisionTimes();
                    BeanUtils.copyProperties(mergeSerialNumber, ckOrderLoanDivisionTimes);
                    ckOrderLoanDivisionTimes.setDataTime(date);
                    Byte isFirstIssue = mergeSerialNumber.getIsFirstIssue();
                    if (isFirstIssue == 1) {
                        ckOrderLoanDivisionTimes.setIsFirstIssue(1);
                    } else if (isFirstIssue == 0) {
                        ckOrderLoanDivisionTimes.setIsFirstIssue(0);
                    }
                    ckOrderLoanDivisionTimesList.add(ckOrderLoanDivisionTimes);*//*
                    ckOrderRecoveryData = null;
                }
                if (!CollectionUtils.isEmpty(ckOrderRecoveryDataArrayList)) {
                    ckOrderRecoveryDataService.insertForeach(ckOrderRecoveryDataArrayList);
                }
             *//*   if (!CollectionUtils.isEmpty(ckOrderLoanDivisionTimesList)) {
                    ckOrderLoanDivisionTimesMapper.insertForEach(ckOrderLoanDivisionTimesList);
                }*//*
                log.info("旧表更新反馈为已合并结束");
            }*/
            log.info("回款出停催及失联数据开始");
            //回款出停催及失联数据
            List<CkStopNoticePerson> ckStopNoticePeopleList = new ArrayList<>();
            Iterator<CkStopNoticePerson> iterator = ckStopNoticePeoples.iterator();
            while (iterator.hasNext()) {
                CkStopNoticePerson next = iterator.next();
                String peopleId = next.getPeopleId();
                List<CkOrderLoanIntelligenceDivision> ckOrderLoanIntelligenceDivisionList = ckOrderLoanIntelligenceDivisionService.selectByPeopleId(peopleId);
                List<CkOrderLoanIntelligenceDivision> ckOrderLoanIntelligenceDivisionList1 = new ArrayList<>();
                for (CkOrderLoanIntelligenceDivision ckOrderLoanIntelligenceDivision : ckOrderLoanIntelligenceDivisionList) {
                    Byte state = ckOrderLoanIntelligenceDivision.getState();
                    if (state != 2) {
                        ckOrderLoanIntelligenceDivisionList1.add(ckOrderLoanIntelligenceDivision);
                    }
                }
                if (CollectionUtils.isEmpty(ckOrderLoanIntelligenceDivisionList1)) {
                    ckStopNoticePeopleList.add(next);
                    iterator.remove();
                    ckOrderLoanIntelligenceDivisionList1.clear();
                }
                ckOrderLoanIntelligenceDivisionList.clear();
            }

            if (!CollectionUtils.isEmpty(ckStopNoticePeopleList)) {
                for (CkStopNoticePerson ckStopNoticePerson : ckStopNoticePeopleList) {
                    ckStopNoticePerson.setIsDelete((byte) 1);
                }
                log.info("回款出停催及失联数据为" + JSON.toJSONString(ckStopNoticePeopleList));
                ckStopNoticePersonService.updateForeachBySeriaNumber(ckStopNoticePeopleList);
            }

            log.info("回款出停催及失联数据结束");
            log.info("旧表停催名单处理开始");
            if (!CollectionUtils.isEmpty(noPaymentList)) {
                noPaymentList = stopNotice(ckStopNoticePeoples, noPaymentList);
            }
            log.info("旧表停催名单处理结束");
            //对旧数据清洗
            if (!CollectionUtils.isEmpty(noPaymentList)) {
                noPaymentList = cleanOldCreditDataDownloadFormData(noPaymentList);
            }
            log.info("旧表未回款规则开始");
            ckOrderLoanIntelligenceDivisionMap = new HashMap<>();
            if (!CollectionUtils.isEmpty(noPaymentList)) {
                for (CkOrderLoanLoad nCkOrderLoanLoad : noPaymentList) {
                    //规则的参数
                    Map<String, String> postParamMap = getPostParam(nCkOrderLoanLoad);
                    log.info("新规则-----------------------参数为" + JSON.toJSONString(postParamMap));
                    //规则的返回值
                    Map<String, String> rulesMap = HttpClientUtils.getPostRules(scanningCleaningConfig.getRulesPath(), postParamMap);
                    log.info("新规则-----------------------访问地址为" + scanningCleaningConfig.getRulesPath());
                    log.info("新规则-----------------------反馈为" + JSON.toJSONString(rulesMap));
                    //String result="2";
                    CkOrderLoanIntelligenceDivision ckOrderLoanIntelligenceDivision = new CkOrderLoanIntelligenceDivision();
                    BeanUtils.copyProperties(nCkOrderLoanLoad, ckOrderLoanIntelligenceDivision);
                    ckOrderLoanIntelligenceDivisionMap = getCkOrderLoanIntelligenceDivisionList(rulesMap,
                            ckOrderLoanIntelligenceDivision, ckOrderLoanIntelligenceDivisionMap, ckLevelMap);
                }
                //旧表根据案件号更新次数
                List<String> serialNumberList = new ArrayList<>();
                Map<String, CkOrderLoanIntelligenceDivision> serialNumberMap = new HashMap<>();
                List<CkOrderLoanIntelligenceDivision> ckOrderLoanIntelligenceDivisions = ckOrderLoanIntelligenceDivisionMap.get("all");
                for (CkOrderLoanIntelligenceDivision ckOrderLoanIntelligenceDivision : ckOrderLoanIntelligenceDivisions) {
                    String serialNumber = ckOrderLoanIntelligenceDivision.getSerialNumber();
                    serialNumberList.add(serialNumber);
                    serialNumberMap.put(serialNumber, ckOrderLoanIntelligenceDivision);
                }
                // 根据案件id获取数据
                List<CkOrderLoanIntelligenceDivision> ckOrderLoanIntelligenceDivisionList = ckOrderLoanIntelligenceDivisionService.selectBySerialNumbers(serialNumberList);
                ckOrderLoanIntelligenceDivisions = new ArrayList<>();
                for (CkOrderLoanIntelligenceDivision ckOrderLoanIntelligenceDivision : ckOrderLoanIntelligenceDivisionList) {
                    String serialNumber = ckOrderLoanIntelligenceDivision.getSerialNumber();
                    Integer collectionTimes = ckOrderLoanIntelligenceDivision.getCollectionTimes();
                    CkOrderLoanIntelligenceDivision ckOrderLoanIntelligenceDivision1 = serialNumberMap.get(serialNumber);
                    Byte outbound = ckOrderLoanIntelligenceDivision1.getOutbound();
                    if (outbound != 4) {
                        if (collectionTimes == null) {
                            collectionTimes = 1;
                        } else {
                            collectionTimes += 1;
                        }
                    }
                    ckOrderLoanIntelligenceDivision1.setCollectionTimes(collectionTimes);
                    ckOrderLoanIntelligenceDivision1.setIsDialed(2);
                    ckOrderLoanIntelligenceDivisions.add(ckOrderLoanIntelligenceDivision1);
                }
                // 根据案件号更新
                //因sql最多缓存64M,故每30000提交一次
                if (!CollectionUtils.isEmpty(ckOrderLoanIntelligenceDivisions)) {
                    int size = ckOrderLoanIntelligenceDivisions.size();
                    if (size > 30000) {
                        int s = size / 30000;
                        for (int i = 1; i <= s; i++) {
                            int b = 30000 * i;
                            List<CkOrderLoanIntelligenceDivision> ckOrderLoanLoads = new ArrayList<>();
                            if (i == s) {
                                for (int j = 30000 * (i - 1); j < size; j++) {
                                    ckOrderLoanLoads.add(ckOrderLoanIntelligenceDivisions.get(j));
                                }
                            } else if (i == 1) {
                                for (int j = 0; j < b; j++) {
                                    ckOrderLoanLoads.add(ckOrderLoanIntelligenceDivisions.get(j));
                                }
                            } else {
                                for (int j = 30000 * (i - 1); j < b; j++) {
                                    ckOrderLoanLoads.add(ckOrderLoanIntelligenceDivisions.get(j));
                                }
                            }
                            ckOrderLoanIntelligenceDivisionService.updateForEach(ckOrderLoanLoads);
                        }
                    } else {
                        ckOrderLoanIntelligenceDivisionService.updateForEach(ckOrderLoanIntelligenceDivisions);
                    }
                }
            }
            List<CkOrderLoanIntelligenceDivision> ckOrderLoanIntelligenceDivisions = ckOrderLoanIntelligenceDivisionMap.get("all");
            //委外筛选处理
            if (!CollectionUtils.isEmpty(ckOrderLoanIntelligenceDivisions)) {
                ckOrderLoanIntelligenceDivisions = outsourcing(ckOrderLoanIntelligenceDivisions);
            }
            log.info("存储到旧表redis");
            List<CreditDataDownloadOldForm> creditDataDownloadOldFormList = new ArrayList<>();
            for (Map.Entry<String, CreditDataDownloadOldForm> stringCreditDataDownloadOldFormEntry : creditDataDownloadOldFormMap.entrySet()) {
                CreditDataDownloadOldForm value = stringCreditDataDownloadOldFormEntry.getValue();
                creditDataDownloadOldFormList.add(value);
            }
            if (redisService.hasKey("tjcssys@oldtable@" + dateStr)) {
                Object o = redisService.get("tjcssys@oldtable@" + dateStr);
                List<CreditDataDownloadOldForm> creditDataDownloadOldForms1 = JSON.parseArray(String.valueOf(o), CreditDataDownloadOldForm.class);
                if (CollectionUtils.isEmpty(creditDataDownloadOldForms1)) {
                    creditDataDownloadOldForms1 = new ArrayList<>();
                }
                creditDataDownloadOldForms1.addAll(creditDataDownloadOldFormList);
                redisService.set("tjcssys@oldtable@" + dateStr, JSON.toJSONString(creditDataDownloadOldForms1));
            } else {
                redisService.set("tjcssys@oldtable@" + dateStr, JSON.toJSONString(creditDataDownloadOldFormList));
            }
            if (!CollectionUtils.isEmpty(ckOrderLoanIntelligenceDivisions)) {
                if (CollectionUtils.isEmpty(ckOrderLoanIntelligenceDivisionAllMap.get("all"))) {
                    ckOrderLoanIntelligenceDivisionAllMap.put("all", ckOrderLoanIntelligenceDivisions);
                } else {
                    List<CkOrderLoanIntelligenceDivision> ckOrderLoanIntelligenceDivisionAllList = ckOrderLoanIntelligenceDivisionAllMap.get("all");
                    ckOrderLoanIntelligenceDivisionAllList.addAll(ckOrderLoanIntelligenceDivisions);
                    ckOrderLoanIntelligenceDivisionAllMap.put("all", ckOrderLoanIntelligenceDivisionAllList);
                }
            }
            List<CkOrderLoanIntelligenceDivision> message = ckOrderLoanIntelligenceDivisionMap.get("message");
            if (CollectionUtils.isEmpty(ckOrderLoanIntelligenceDivisionAllMap.get("message"))) {
                ckOrderLoanIntelligenceDivisionAllMap.put("message", message);
            } else {
                List<CkOrderLoanIntelligenceDivision> ckOrderLoanIntelligenceDivisionAllList = ckOrderLoanIntelligenceDivisionAllMap.get("message");
                ckOrderLoanIntelligenceDivisionAllList.addAll(message);
                ckOrderLoanIntelligenceDivisionAllMap.put("message", ckOrderLoanIntelligenceDivisionAllList);
            }

            log.info("旧表未回款规则结束");
            creditDataDownloadOldFormMap.clear();
            return ckOrderLoanIntelligenceDivisionAllMap;
        } else {
            log.info("旧表未回款数据为空");
            return ckOrderLoanIntelligenceDivisionAllMap;
        }
    }

    /**
     * 催收员成绩表存储
     *
     * @param paymentList
     */
    private void saveCollector(List<CkOrderLoanLoad> paymentList) {
        //获取昨天的日期
        String yesterday = getYesterday();
        //获取昨天的返回数据
        List<CkOrderRecoveryData> ckOrderRecoveryDataLike = ckOrderRecoveryDataService.findByNotificationMethodAndDateTime((byte) 3, yesterday);
        Map<String, CkOrderRecoveryData> ckOrderRecoveryDataHashMap = new HashMap<>();
        List<String> serialNumbers = new ArrayList<>();
        for (CkOrderRecoveryData ckOrderRecoveryData : ckOrderRecoveryDataLike) {
            String serialNumber = ckOrderRecoveryData.getSerialNumber();
            serialNumbers.add(serialNumber);
            ckOrderRecoveryDataHashMap.put(serialNumber, ckOrderRecoveryData);
        }
        List<CkOrderAchievementForm> ckOrderAchievementFormList = new ArrayList<>();
        //获取催收员
        Map<String, CkOrderAchievementForm> ckOrderAchievementFormMap = ckOrderAchievementFormService.selectAll();
        if (ckOrderAchievementFormMap != null) {
            for (CkOrderLoanLoad ckOrderLoanLoad : paymentList) {
                String serialNumber = ckOrderLoanLoad.getSerialNumber();
                if (serialNumbers.contains(serialNumber)) {
                    Double repaymentAmount = ckOrderLoanLoad.getRepaymentAmount();
                    CkOrderRecoveryData ckOrderRecoveryData = ckOrderRecoveryDataHashMap.get(serialNumber);
                    String customerServiceId = ckOrderRecoveryData.getCustomerServiceId();
                    CkOrderAchievementForm ckOrderAchievementForm = ckOrderAchievementFormMap.get(customerServiceId);
                    if (ckOrderAchievementForm != null) {
                        String amountRecovered = ckOrderAchievementForm.getAmountRecovered();
                        if (StringUtils.isEmpty(amountRecovered)) {
                            amountRecovered = "0";
                        }
                        String s1 = new BigDecimal(amountRecovered).add(new BigDecimal(repaymentAmount)).toString();
                        ckOrderAchievementForm.setAmountRecovered(s1);
                        String amountOverdue = ckOrderAchievementForm.getAmountOverdue();
                        String s = new BigDecimal(s1).divide(new BigDecimal(amountOverdue), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).toString();
                        ckOrderAchievementForm.setRateRecovered(s);
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String format = simpleDateFormat.format(new Date());
                        ckOrderAchievementForm.setDate(format);
                        ckOrderAchievementFormList.add(ckOrderAchievementForm);
                    }
                }
            }
        }
        if (!CollectionUtils.isEmpty(ckOrderAchievementFormList)) {
            ckOrderAchievementFormService.updateForeach(ckOrderAchievementFormList);
        }

    }

    /**
     * 获取昨天一天
     *
     * @return
     */
    private String getYesterday() {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, -1);
        Date time = instance.getTime();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(time);
        return format;
    }

    /**
     * 对于新表的处理
     *
     * @param nCkOrderLoanLoads                     log表数据
     * @param creditDataDownloadNewForms            大数据下拉新表数据
     * @param ckStopNoticePeoples                   停催和失联表数据
     * @param ckOrderLoanIntelligenceDivisionMap    智能分案list
     * @param ckLevelMap                            等级表
     * @param ckOrderLoanIntelligenceDivisionAllMap 智能分案全部表
     * @return
     * @throws Exception
     */
    private Map<String, List<CkOrderLoanIntelligenceDivision>> nTableCaseProcessing(List<CkOrderLoanLoad> nCkOrderLoanLoads,
                                                                                    List<CreditDataDownloadNewForm> creditDataDownloadNewForms,
                                                                                    List<CkStopNoticePerson> ckStopNoticePeoples,
                                                                                    Map<String, List<CkOrderLoanIntelligenceDivision>> ckOrderLoanIntelligenceDivisionMap,
                                                                                    Map<String, List<CkLevel>> ckLevelMap,
                                                                                    Map<String, List<CkOrderLoanIntelligenceDivision>> ckOrderLoanIntelligenceDivisionAllMap) throws Exception {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String dateStr = simpleDateFormat.format(date);
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr1 = simpleDateFormat1.format(date);
        nCkOrderLoanLoads = new ArrayList<>();
        log.info("执行新文件存储清洗工作");
        List<CkOrderLoanLoad> finalNCkOrderLoanLoads = nCkOrderLoanLoads;
        creditDataDownloadNewForms.stream().forEach(creditDataDownloadNewForm ->
        {
            CkOrderLoanLoad ckOrderLoanLoad = new CkOrderLoanLoad();
            creditDataDownloadNewForm = getBaseInfomation(creditDataDownloadNewForm);
            BeanUtils.copyProperties(creditDataDownloadNewForm, ckOrderLoanLoad);
            ckOrderLoanLoad.setDataTime(dateStr1);
            finalNCkOrderLoanLoads.add(ckOrderLoanLoad);
            ckOrderLoanLoad = null;
        });
        //因sql最多缓存64M,故每30000提交一次
        if (!CollectionUtils.isEmpty(nCkOrderLoanLoads)) {
            int size = nCkOrderLoanLoads.size();
            if (size > 30000) {
                int s = size / 30000;
                for (int i = 1; i <= s; i++) {
                    int b = 30000 * i;
                    List<CkOrderLoanLoad> ckOrderLoanLoads = new ArrayList<>();
                    if (i == s) {
                        for (int j = 30000 * (i - 1); j < size; j++) {
                            ckOrderLoanLoads.add(nCkOrderLoanLoads.get(j));
                        }
                    } else if (i == 1) {
                        for (int j = 0; j < b; j++) {
                            ckOrderLoanLoads.add(nCkOrderLoanLoads.get(j));
                        }
                    } else {
                        for (int j = 30000 * (i - 1); j < b; j++) {
                            ckOrderLoanLoads.add(nCkOrderLoanLoads.get(j));
                        }
                    }
                    ckOrderLoanLoadService.insertForeach(ckOrderLoanLoads);
                }
            } else {
                ckOrderLoanLoadService.insertForeach(nCkOrderLoanLoads);
            }
        }
        log.info("新表插入大数据信息表(信贷)成功");
        log.info("停催名单处理开始");
        nCkOrderLoanLoads = stopNotice(ckStopNoticePeoples, nCkOrderLoanLoads);
        log.info("停催名单处理结束");
        log.info("新表规则开始");
        ckOrderLoanIntelligenceDivisionMap = new HashMap<>();
        for (CkOrderLoanLoad nCkOrderLoanLoad : nCkOrderLoanLoads) {
            //规则的参数
            Map<String, String> postParamMap = getPostParam(nCkOrderLoanLoad);
            log.info("新规则-----------------------参数为" + JSON.toJSONString(postParamMap));
            //规则Url
            String rulesPath = scanningCleaningConfig.getRulesPath();
            //规则返回结果
            Map<String, String> rulesMap = HttpClientUtils.getPostRules(rulesPath, postParamMap);
            log.info("新规则-----------------------访问地址为" + scanningCleaningConfig.getRulesPath());
            //String result ="1";
            log.info("新规则-----------------------反馈结果为" + JSON.toJSONString(rulesMap));
            //智能分案bean
            CkOrderLoanIntelligenceDivision ckOrderLoanIntelligenceDivision = new CkOrderLoanIntelligenceDivision();
            BeanUtils.copyProperties(nCkOrderLoanLoad, ckOrderLoanIntelligenceDivision);
            ckOrderLoanIntelligenceDivision.setIsDialed(2);
            ckOrderLoanIntelligenceDivisionMap = getCkOrderLoanIntelligenceDivisionList(rulesMap,
                    ckOrderLoanIntelligenceDivision, ckOrderLoanIntelligenceDivisionMap, ckLevelMap);
        }
        nCkOrderLoanLoads.clear();
        nCkOrderLoanLoads = null;
        List<CkOrderLoanIntelligenceDivision> ckOrderLoanIntelligenceDivisions = ckOrderLoanIntelligenceDivisionMap.get("all");
        //	批量插入数据库
        log.info("插入到智能催收表中开始");
        if (!CollectionUtils.isEmpty(ckOrderLoanIntelligenceDivisions)) {
            //因sql最多缓存64M,故每30000提交一次
            if (!CollectionUtils.isEmpty(ckOrderLoanIntelligenceDivisions)) {
                int size = ckOrderLoanIntelligenceDivisions.size();
                if (size > 30000) {
                    int s = size / 30000;
                    for (int i = 1; i <= s; i++) {
                        int b = 30000 * i;
                        List<CkOrderLoanIntelligenceDivision> ckOrderLoanIntelligenceDivisionList = new ArrayList<>();
                        if (i == s) {
                            for (int j = 30000 * (i - 1); j < size; j++) {
                                ckOrderLoanIntelligenceDivisionList.add(ckOrderLoanIntelligenceDivisions.get(j));
                            }
                        } else if (i == 1) {
                            for (int j = 0; j < b; j++) {
                                ckOrderLoanIntelligenceDivisionList.add(ckOrderLoanIntelligenceDivisions.get(j));
                            }
                        } else {
                            for (int j = 30000 * (i - 1); j < b; j++) {
                                ckOrderLoanIntelligenceDivisionList.add(ckOrderLoanIntelligenceDivisions.get(j));
                            }
                        }
                        ckOrderLoanIntelligenceDivisionService.insertForeach(ckOrderLoanIntelligenceDivisionList);
                    }
                } else {
                    ckOrderLoanIntelligenceDivisionService.insertForeach(ckOrderLoanIntelligenceDivisions);
                }
            }
        }
        List<CkOrderLoanIntelligenceDivision> noOutbounds = ckOrderLoanIntelligenceDivisionMap.get("noOutbound");
        if (!CollectionUtils.isEmpty(noOutbounds)) {
            ckOrderLoanIntelligenceDivisionService.insertForeach(noOutbounds);
        }
        //委外筛选处理
        if (!CollectionUtils.isEmpty(ckOrderLoanIntelligenceDivisions)) {
            ckOrderLoanIntelligenceDivisions = outsourcing(ckOrderLoanIntelligenceDivisions);
        }
        //存入到新表redis
        if (redisService.hasKey("tjcssys@newtable@" + dateStr)) {
            Object o = redisService.get("tjcssys@newtable@" + dateStr);
            String s = String.valueOf(o);
            List<CreditDataDownloadNewForm> creditDataDownloadNewForms1 = JSON.parseArray(s, CreditDataDownloadNewForm.class);
            if (CollectionUtils.isEmpty(creditDataDownloadNewForms1)) {
                creditDataDownloadNewForms1 = new ArrayList<>();
            }
            creditDataDownloadNewForms1.addAll(creditDataDownloadNewForms);
            redisService.set("tjcssys@newtable@" + dateStr, JSON.toJSONString(creditDataDownloadNewForms1));
        } else {
            redisService.set("tjcssys@newtable@" + dateStr, JSON.toJSONString(creditDataDownloadNewForms));
        }

        ckOrderLoanIntelligenceDivisionAllMap.put("all", ckOrderLoanIntelligenceDivisions);
        ckOrderLoanIntelligenceDivisionAllMap.put("message", ckOrderLoanIntelligenceDivisionMap.get("message"));

        log.info("插入到智能催收表中结束");
        log.info("新表规则结束");
        log.info("删除下载新表数据库内容开始");
        creditDataDownloadNewFormService.deleteList(creditDataDownloadNewForms);
        creditDataDownloadNewForms.clear();
        creditDataDownloadNewForms = null;
        log.info("删除下载新表数据库内容结束");
        return ckOrderLoanIntelligenceDivisionAllMap;
    }

    /**
     * 码值(基础信息)
     *
     * @param creditDataDownloadNewForm
     * @return
     */
    private CreditDataDownloadNewForm getBaseInfomation(CreditDataDownloadNewForm creditDataDownloadNewForm) {
        //婚姻状况
        String maritalStatus = creditDataDownloadNewForm.getMaritalStatus();
        if (StringUtils.isNotEmpty(maritalStatus)) {
            String marital = baseInformationUtils.getMarital(maritalStatus);
            creditDataDownloadNewForm.setMaritalStatus(marital);
        }
        //性别
        String sex = creditDataDownloadNewForm.getSex();
        if (StringUtils.isNotEmpty(sex)) {
            creditDataDownloadNewForm.setSex(baseInformationUtils.getSexStr(sex));
        }
        //学历
        String education = creditDataDownloadNewForm.getEducation();
        if (StringUtils.isNotEmpty(education)) {
            creditDataDownloadNewForm.setEducation(baseInformationUtils.getEducation(education));
        }
        return creditDataDownloadNewForm;
    }

    /**
     * 因短信无返回信息,故都承诺回款
     *
     * @param handleMap
     * @param ckOrderLoanIntelligenceDivisionAllMap
     */
    private void saveMessageRecoverResult(Map<String, Map<String, List<CkOrderLoanIntelligenceDivision>>> handleMap,
                                          Map<String, List<CkOrderLoanIntelligenceDivision>> ckOrderLoanIntelligenceDivisionAllMap) {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr1 = simpleDateFormat1.format(date);
        String code = ckFeedbackTableMapper.selectByChinese("承诺还款");
        Map<String, List<CkOrderLoanIntelligenceDivision>> messageMap = handleMap.get("金信通");
        //分别把人工和智能的身份证号加入list
        List<CkOrderLoanIntelligenceDivision> message = ckOrderLoanIntelligenceDivisionAllMap.get("message");
        List<String> peopleIds = new ArrayList<>();
        if (!CollectionUtils.isEmpty(message)) {
            for (CkOrderLoanIntelligenceDivision ckOrderLoanIntelligenceDivision : message) {
                String peopleId = ckOrderLoanIntelligenceDivision.getPeopleId();
                peopleIds.add(peopleId);
            }
        }
        if (messageMap != null) {
            List<CkOrderLoanIntelligenceDivision> ckOrderLoanIntelligenceDivisions = new ArrayList<>();
            for (Map.Entry<String, List<CkOrderLoanIntelligenceDivision>> stringListEntry : messageMap.entrySet()) {
                List<CkOrderLoanIntelligenceDivision> value = stringListEntry.getValue();
                ckOrderLoanIntelligenceDivisions.addAll(value);
            }
            List<CkOrderRecoveryData> ckOrderRecoveryDatas = new ArrayList<>();
            for (CkOrderLoanIntelligenceDivision ckOrderLoanIntelligenceDivision : ckOrderLoanIntelligenceDivisions) {
                String peopleId = ckOrderLoanIntelligenceDivision.getPeopleId();
                if (!peopleIds.contains(peopleId)) {
                    CkOrderRecoveryData ckOrderRecoveryData = new CkOrderRecoveryData();
                    BeanUtils.copyProperties(ckOrderLoanIntelligenceDivision, ckOrderRecoveryData);
                    ckOrderRecoveryData.setNotificationMethod((byte) 1);
                    ckOrderRecoveryData.setFeedbackCode(code);
                    ckOrderRecoveryData.setSendTime(dateStr1);
                    ckOrderRecoveryDatas.add(ckOrderRecoveryData);
                    ckOrderRecoveryData = null;
                }
            }
            if (!CollectionUtils.isEmpty(ckOrderRecoveryDatas)) {
                ckOrderRecoveryDataMapper.insertForeach(ckOrderRecoveryDatas);
            }
        }
    }

    /**
     * 写txt文件
     *
     * @param fileName
     * @param txtPath
     * @param content
     */
    public void writeLineTxtFile(String fileName, String txtPath, List<String> content, String suffix) {
        String fileNamePath = new StringBuilder(txtPath).append(fileName).append(suffix).toString();
        log.info("处理短信模板信息,生成" + fileNamePath + ",文件开始");
        FileOutputStream out = null;
        OutputStreamWriter outWriter = null;
        BufferedWriter bufWrite = null;
        try {
            out = new FileOutputStream(fileNamePath);
            outWriter = new OutputStreamWriter(out, "GBK");
            bufWrite = new BufferedWriter(outWriter);
            for (int i = 0; i < content.size(); i++) {
                bufWrite.write(content.get(i) + "\r\n");
            }
        } catch (Exception e) {
            log.error("处理短信模板信息,生成" + fileNamePath + ",文件出错", e);
        } finally {
            try {
                if (bufWrite != null) {
                    bufWrite.close();
                }
                if (outWriter != null) {
                    outWriter.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (Exception e) {
                log.error("处理短信模板信息,生成" + fileNamePath + ",文件出错", e);
            }
        }
        log.info("处理短信模板信息,生成" + fileNamePath + ",文件结束");
      /*  log.info("使用ftp上传txt文件,上传" + fileNamePath + ",文件开始");
        FtpUtils ftpUtils = new FtpUtils();
        ftpUtils.uploadFile(scanningCleaningConfig.getFtpUrl(),fileName,fileNamePath);
        log.info("使用ftp上传txt文件,上传" + fileNamePath + ",文件结束");*/
    }

    /**
     * 获取txt文件信息
     *
     * @param handleMap
     * @return
     */
    private Map<String, List<String>> getInformationTxt(Map<String, Map<String,
            List<CkOrderLoanIntelligenceDivision>>> handleMap) throws Exception {
        //存储全部文件名的map
        Map<String, List<String>> txtMaps = getTxtMap();
        //存储多个字段的list
        List<String> txtNameList = getTxtList();
        if (handleMap.containsKey("金信通")) {
            Map<String, List<CkOrderLoanIntelligenceDivision>> infomationMap = handleMap.get("金信通");
            for (Map.Entry<String, List<CkOrderLoanIntelligenceDivision>> stringListEntry : infomationMap.entrySet()) {
                List<CkOrderLoanIntelligenceDivision> value = stringListEntry.getValue();
                for (CkOrderLoanIntelligenceDivision ckOrderLoanIntelligenceDivision : value) {
                    txtMaps = getInfomationStr(ckOrderLoanIntelligenceDivision, txtMaps, txtNameList);
                }
            }
        }
        return txtMaps;
    }

    /**
     * 获取带有额度的txt文件名
     *
     * @return
     */
    private List<String> getTxtList() throws Exception {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String dateStr = simpleDateFormat.format(date);
        List<String> txtNameLsit = new ArrayList<>();
        txtNameLsit.add(scanningCleaningConfig.getTxtM102Path() + dateStr);
        txtNameLsit.add(scanningCleaningConfig.getTxtM103Path() + dateStr);
        txtNameLsit.add(scanningCleaningConfig.getTxtM104Path() + dateStr);
        txtNameLsit.add(scanningCleaningConfig.getTxtM202Path() + dateStr);
        txtNameLsit.add(scanningCleaningConfig.getTxtM203Path() + dateStr);
        txtNameLsit.add(scanningCleaningConfig.getTxtM302Path() + dateStr);
        txtNameLsit.add(scanningCleaningConfig.getTxtM303Path() + dateStr);
        txtNameLsit.add(scanningCleaningConfig.getTxtM304Path() + dateStr);
        return txtNameLsit;
    }

    /**
     * 获取所有文件名
     *
     * @return
     */
    private Map<String, List<String>> getTxtMap() throws Exception {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String dateStr = simpleDateFormat.format(date);
        Map<String, List<String>> txtMaps = new HashMap<>();
        txtMaps.put(scanningCleaningConfig.getTxtM101Path() + dateStr, null);
        txtMaps.put(scanningCleaningConfig.getTxtM102Path() + dateStr, null);
        txtMaps.put(scanningCleaningConfig.getTxtM103Path() + dateStr, null);
        txtMaps.put(scanningCleaningConfig.getTxtM104Path() + dateStr, null);
        txtMaps.put(scanningCleaningConfig.getTxtM201Path() + dateStr, null);
        txtMaps.put(scanningCleaningConfig.getTxtM202Path() + dateStr, null);
        txtMaps.put(scanningCleaningConfig.getTxtM203Path() + dateStr, null);
        txtMaps.put(scanningCleaningConfig.getTxtM301Path() + dateStr, null);
        txtMaps.put(scanningCleaningConfig.getTxtM302Path() + dateStr, null);
        txtMaps.put(scanningCleaningConfig.getTxtM303Path() + dateStr, null);
        txtMaps.put(scanningCleaningConfig.getTxtM304Path() + dateStr, null);
        return txtMaps;
    }

    private Map<String, List<String>> getInfomationStr(CkOrderLoanIntelligenceDivision ckOrderLoanIntelligenceDivision,
                                                       Map<String, List<String>> txtMaps, List<String> txtNameList) throws Exception {
        //发送短信模板号
        String smsTemplate = ckOrderLoanIntelligenceDivision.getSmsTemplate();
        //手机号
        String phoneNum = ckOrderLoanIntelligenceDivision.getPhoneNum();
        //姓名
        String name = ckOrderLoanIntelligenceDivision.getName();
        //产品名称
        String productName = ckOrderLoanIntelligenceDivision.getProductName();
        //逾期金额
        Double overdueAmount = ckOrderLoanIntelligenceDivision.getOverdueAmount();
        //逾期天数
        Integer overdueDay = ckOrderLoanIntelligenceDivision.getOverdueDay();
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(phoneNum).append("|")
                .append(name).append("|")
                .append(productName).append("|")
                .append(overdueAmount);
        String txtName = null;
        for (String s : txtMaps.keySet()) {
            if (s.contains(smsTemplate)) {
                txtName = s;
                break;
            }
        }
        if (txtNameList.contains(txtName)) {
            stringBuilder.append("|").append(overdueDay).append("|");
        } else {
            stringBuilder.append("|");
        }
        List<String> txtList = null;
        if (txtMaps.get(txtName) == null) {
            txtList = new ArrayList<>();
        } else {
            txtList = txtMaps.get(txtName);
        }
        txtList.add(stringBuilder.toString());
        txtMaps.put(txtName, txtList);
        return txtMaps;
    }

    /**
     * 对失联名单的处理
     *
     * @param ckStopNoticePeoples
     * @param noPaymentList
     * @return
     */
    private List<CkOrderLoanLoad> stopNotice(List<CkStopNoticePerson> ckStopNoticePeoples, List<CkOrderLoanLoad> noPaymentList) throws Exception {
        if (!CollectionUtils.isEmpty(ckStopNoticePeoples)) {
            List<String> peopleIdList = new ArrayList<>();
            List<String> phoneNumberList = new ArrayList<>();
            for (CkStopNoticePerson ckStopNoticePerson : ckStopNoticePeoples) {
                String peopleId = ckStopNoticePerson.getPeopleId();
                String phoneNum = ckStopNoticePerson.getPhoneNum();
                peopleIdList.add(peopleId);
                phoneNumberList.add(phoneNum);

            }
            Iterator<CkOrderLoanLoad> iterator = noPaymentList.iterator();
            while (iterator.hasNext()) {
                CkOrderLoanLoad ckOrderLoanLoad = iterator.next();
                String peopleId = ckOrderLoanLoad.getPeopleId();
                String phoneNum = ckOrderLoanLoad.getPhoneNum();
                if (peopleIdList.contains(peopleId) /*&& phoneNumberList.contains(phoneNum)*/) {
                    iterator.remove();
                }
            }
        }
        return noPaymentList;
    }

    /**
     * 生成json文件
     *
     * @param filePath
     * @param sets
     * @return
     * @throws Exception
     */
    private boolean writeJsonFile(String filePath, String sets) throws Exception {
        FileWriter fw;
        fw = new FileWriter(filePath);
        PrintWriter out = new PrintWriter(fw);
        try {
            out.write(sets);
            out.println();
            return true;
        } catch (Exception e) {
            throw e;
        } finally {
            fw.close();
            out.close();
        }
    }

    /**
     * 重新生成规则
     *
     * @param ckOrderLoanIntelligenceDivisions
     * @return
     */
    private Map<String, Map<String, List<CkOrderLoanIntelligenceDivision>>> getHandleMap(List<CkOrderLoanIntelligenceDivision> ckOrderLoanIntelligenceDivisions) throws Exception {
        //外层的map
        Map<String, Map<String, List<CkOrderLoanIntelligenceDivision>>> resultMap = new HashMap<>();
        //内层的map
        Map<String, List<CkOrderLoanIntelligenceDivision>> params = new HashMap<>();
        for (CkOrderLoanIntelligenceDivision ckOrderLoanIntelligenceDivision : ckOrderLoanIntelligenceDivisions) {
            String peopleId = ckOrderLoanIntelligenceDivision.getPeopleId();
            if (params.get(peopleId) == null) {
                List<CkOrderLoanIntelligenceDivision> ckOrderLoanIntelligenceDivisionList = new ArrayList<>();
                ckOrderLoanIntelligenceDivisionList.add(ckOrderLoanIntelligenceDivision);
                params.put(peopleId, ckOrderLoanIntelligenceDivisionList);
            } else {
                List<CkOrderLoanIntelligenceDivision> ckOrderLoanIntelligenceDivisionList = params.get(peopleId);
                ckOrderLoanIntelligenceDivisionList.add(ckOrderLoanIntelligenceDivision);
                params.put(peopleId, ckOrderLoanIntelligenceDivisionList);
            }
        }
        for (Map.Entry<String, List<CkOrderLoanIntelligenceDivision>> stringListEntry : params.entrySet()) {
            List<CkOrderLoanIntelligenceDivision> value = stringListEntry.getValue();
            Byte b = 1;
            for (CkOrderLoanIntelligenceDivision ckOrderLoanIntelligenceDivision : value) {
                Byte outbound = ckOrderLoanIntelligenceDivision.getOutbound();
                if (b <= outbound) {
                    b = outbound;
                }
            }
            for (CkOrderLoanIntelligenceDivision ckOrderLoanIntelligenceDivision : value) {
                if (b == 3 || b == 2) {
                    if (b == 3) {
                        ckOrderLoanIntelligenceDivision.setIsDelete(null);
                    }
                    ckOrderLoanIntelligenceDivision.setSmsTemplate(null);
                }
                resultMap = getRulesMap(ckOrderLoanIntelligenceDivision, b, resultMap);
            }
        }
        return resultMap;
    }

    /**
     * 生成规则Map
     *
     * @param ckOrderLoanIntelligenceDivision
     * @param result
     * @param rulesMap
     * @return
     */
    private Map<String, Map<String, List<CkOrderLoanIntelligenceDivision>>> getRulesMap(CkOrderLoanIntelligenceDivision ckOrderLoanIntelligenceDivision,
                                                                                        Byte result,
                                                                                        Map<String, Map<String, List<CkOrderLoanIntelligenceDivision>>> rulesMap) throws Exception {
        String resultStr = null;
        switch (result) {
            case (byte) 1:
                resultStr = "金信通";
                break;
            case (byte) 2:
                resultStr = "智能外呼";
                break;
            case (byte) 3:
                resultStr = "人工外呼";
                break;
            case (byte) 4:
                resultStr = "委外";
                break;
            case (byte) 5:
                resultStr = "错误";
                break;
        }
        String peopleId = ckOrderLoanIntelligenceDivision.getPeopleId();
        if (rulesMap.get(resultStr) == null) {
            List<CkOrderLoanIntelligenceDivision> ckOrderLoanIntelligenceDivisions = new ArrayList<>();
            Map<String, List<CkOrderLoanIntelligenceDivision>> peopleIdMap = new HashMap<>();
            ckOrderLoanIntelligenceDivisions.add(ckOrderLoanIntelligenceDivision);
            peopleIdMap.put(peopleId, ckOrderLoanIntelligenceDivisions);
            rulesMap.put(resultStr, peopleIdMap);
        } else {
            Map<String, List<CkOrderLoanIntelligenceDivision>> peopleIdMap = rulesMap.get(resultStr);
            if (peopleIdMap.get(peopleId) == null) {
                List<CkOrderLoanIntelligenceDivision> ckOrderLoanIntelligenceDivisions = new ArrayList<>();
                ckOrderLoanIntelligenceDivisions.add(ckOrderLoanIntelligenceDivision);
                peopleIdMap.put(peopleId, ckOrderLoanIntelligenceDivisions);
                rulesMap.put(resultStr, peopleIdMap);
            } else {
                List<CkOrderLoanIntelligenceDivision> ckOrderLoanIntelligenceDivisions = peopleIdMap.get(peopleId);
                ckOrderLoanIntelligenceDivisions.add(ckOrderLoanIntelligenceDivision);
                peopleIdMap.put(peopleId, ckOrderLoanIntelligenceDivisions);
                rulesMap.put(resultStr, peopleIdMap);
            }
        }
        return rulesMap;

    }

    /**
     * 获取智能分案信息list
     *
     * @param rulesMap
     * @param ckOrderLoanIntelligenceDivision
     * @param ckOrderLoanIntelligenceDivisionMap
     * @return
     */
    private Map<String, List<CkOrderLoanIntelligenceDivision>> getCkOrderLoanIntelligenceDivisionList(Map<String, String> rulesMap,
                                                                                                      CkOrderLoanIntelligenceDivision ckOrderLoanIntelligenceDivision,
                                                                                                      Map<String, List<CkOrderLoanIntelligenceDivision>> ckOrderLoanIntelligenceDivisionMap,
                                                                                                      Map<String, List<CkLevel>> ckLevelMap) throws Exception {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr1 = simpleDateFormat1.format(date);
        String outbound = rulesMap.get("outbound");


        if (!outbound.equalsIgnoreCase("0")) {
            //全部list
            List<CkOrderLoanIntelligenceDivision> ckOrderLoanIntelligenceDivisions = null;
            if (CollectionUtils.isEmpty(ckOrderLoanIntelligenceDivisionMap.get("all"))) {
                ckOrderLoanIntelligenceDivisions = new ArrayList<>();
            } else {
                ckOrderLoanIntelligenceDivisions = ckOrderLoanIntelligenceDivisionMap.get("all");
            }
            String[] split = outbound.split(",");
            //短信list
            List<CkOrderLoanIntelligenceDivision> ckOrderLoanIntelligenceDivisionMessages = null;
            if (CollectionUtils.isEmpty(ckOrderLoanIntelligenceDivisionMap.get("message"))) {
                ckOrderLoanIntelligenceDivisionMessages = new ArrayList<>();
            } else {
                ckOrderLoanIntelligenceDivisionMessages = ckOrderLoanIntelligenceDivisionMap.get("message");
            }
            for (int i = 0; i < split.length; i++) {
                byte result = Byte.parseByte(split[i]);
                if (result == 1) {
                    String note = rulesMap.get("note");
                    ckOrderLoanIntelligenceDivision.setSmsTemplate(note);
                }
                //风险等级
                if (!outbound.equalsIgnoreCase("0")) {
                    String riskLevel = rulesMap.get("riskLevel");
                    ckOrderLoanIntelligenceDivision.setRiskLevel(riskLevel);
                }
                //逾期等级
                Integer overdueDay = ckOrderLoanIntelligenceDivision.getOverdueDay();
                List<CkLevel> days = ckLevelMap.get("day");
                String overdueGrade = null;
                for (CkLevel ckLevel : days) {
                    Integer start = ckLevel.getStart();
                    Integer end = ckLevel.getEnd();
                    if (overdueDay >= start && overdueDay <= end) {
                        overdueGrade = ckLevel.getPname();
                        break;
                    }
                }

                //催收优先级
                String collectionPriority = null;
                switch (overdueGrade) {
                    case "M1":
                        collectionPriority = "1";
                        break;
                    case "M2":
                        collectionPriority = "2";
                        break;
                    case "M3":
                    case "M4":
                    case "M5":
                    case "M6":
                        collectionPriority = "3";
                        break;
                }
                //客群细分标签
                String customersClassify = rulesMap.get("CustomersClassify");
                ckOrderLoanIntelligenceDivision.setCustomerLabel(customersClassify);
                ckOrderLoanIntelligenceDivision.setCollectionPriority(collectionPriority);
                ckOrderLoanIntelligenceDivision.setOverdueGrade(overdueGrade);
                ckOrderLoanIntelligenceDivision.setScriptTemplate(overdueGrade);
                if (result == 4) {
                    ckOrderLoanIntelligenceDivision.setCollectionTimes(0);
                } else {
                    ckOrderLoanIntelligenceDivision.setCollectionTimes(1);
                }
                ckOrderLoanIntelligenceDivision.setDataTime(dateStr1);
                ckOrderLoanIntelligenceDivision.setOutbound(result);
                ckOrderLoanIntelligenceDivision.setDivision((byte) 2);
                if (split.length == 2) {
                    if (result == 1) {
                        ckOrderLoanIntelligenceDivisionMessages.add(ckOrderLoanIntelligenceDivision);
                    } else {
                        CkOrderLoanIntelligenceDivision ckOrderLoanIntelligenceDivision1 = new CkOrderLoanIntelligenceDivision();
                        BeanUtils.copyProperties(ckOrderLoanIntelligenceDivision, ckOrderLoanIntelligenceDivision1);
                        ckOrderLoanIntelligenceDivisions.add(ckOrderLoanIntelligenceDivision1);
                        ckOrderLoanIntelligenceDivision1 = null;
                    }
                } else {
                    ckOrderLoanIntelligenceDivisions.add(ckOrderLoanIntelligenceDivision);
                }
            }
            ckOrderLoanIntelligenceDivisionMap.put("message", ckOrderLoanIntelligenceDivisionMessages);
            ckOrderLoanIntelligenceDivisionMap.put("all", ckOrderLoanIntelligenceDivisions);
        } else {
            List<CkOrderLoanIntelligenceDivision> noOutbounds = null;
            if (ckOrderLoanIntelligenceDivisionMap.get("noOutbound") == null) {
                noOutbounds = new ArrayList<>();
            } else {
                noOutbounds = ckOrderLoanIntelligenceDivisionMap.get("noOutbound");
            }
            noOutbounds.add(ckOrderLoanIntelligenceDivision);
            ckOrderLoanIntelligenceDivisionMap.put("noOutbound", noOutbounds);
        }
        ckOrderLoanIntelligenceDivision = null;
        return ckOrderLoanIntelligenceDivisionMap;
    }

    /**
     * 设置规则参数
     *
     * @param nCkOrderLoanLoads
     * @return
     */
    private Map<String, String> getPostParam(CkOrderLoanLoad nCkOrderLoanLoads) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("projectCode", "rule_cord");
        paramMap.put("enterPoint", scanningCleaningConfig.getEnterPoint());
        Map<String, Object> nCkOrderLoanLoadMap = new HashMap<>();
        Map<String, Object> paramsMap = new HashMap<>();
        Integer score = nCkOrderLoanLoads.getScore();
        Double overdueAmount = nCkOrderLoanLoads.getOverdueAmount();
        Integer overdueDay = nCkOrderLoanLoads.getOverdueDay();
        Byte isFirstIssue = nCkOrderLoanLoads.getIsFirstIssue();
        paramsMap.put("score", score);
        paramsMap.put("overdueAmount", overdueAmount);
        paramsMap.put("overdueDay", overdueDay);
        paramsMap.put("isFirstIssue", isFirstIssue);
        nCkOrderLoanLoadMap.put("resful", paramsMap);
        paramMap.put("businessInput", nCkOrderLoanLoadMap);
        String paramJson = JSON.toJSONString(paramMap);
        Map<String, String> map = JSONUtils.jsonToMap(paramJson);
        return map;
    }

    /*    *//**
     * 从csv按条获取组成log表数据
     *
     * @param string
     * @return
     *//*
    private CkOrderLoanLoad getCkOrderLoanLoad(String[] string) {
        CkOrderLoanLoad ckOrderLoanLoad = new CkOrderLoanLoad();
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        //案件流水号
        ckOrderLoanLoad.setSerialNumber(string[0]);
        //客户号
        ckOrderLoanLoad.setCustomerId(string[1]);
        //贷款合同号
        ckOrderLoanLoad.setContractNum(string[2]);
        //贷款借据号
        ckOrderLoanLoad.setReceiptNum(string[3]);
        //身份证号
        ckOrderLoanLoad.setPeopleId(string[4]);
        //姓名
        ckOrderLoanLoad.setName(string[5]);
        //年龄
        if (StringUtils.isNotEmpty(string[6])) {
            ckOrderLoanLoad.setAge(Integer.parseInt(string[6]));
        } else {
            ckOrderLoanLoad.setAge(null);
        }
        //性别
        ckOrderLoanLoad.setSex(string[7]);
        //学历
        ckOrderLoanLoad.setEducation(string[8]);
        //婚姻状况
        ckOrderLoanLoad.setMaritalStatus(string[9]);
        //贷款所属银行
        ckOrderLoanLoad.setBank(string[10]);
        //逾期金额
        ckOrderLoanLoad.setOverdueAmount(string[11]);
        //逾期天数
        if (StringUtils.isNotEmpty(string[12])) {
            ckOrderLoanLoad.setOverdueDay(Integer.parseInt(string[12]));
        } else {
            ckOrderLoanLoad.setOverdueDay(null);
        }
        //逾期本金
        ckOrderLoanLoad.setOverduePrincipal(string[13]);
        //产品名称
        ckOrderLoanLoad.setProductName(string[14]);
        //申请时间
        ckOrderLoanLoad.setApplicationTime(string[15]);
        //逾期罚息
        ckOrderLoanLoad.setLateCharge(string[16]);
        //电话
        ckOrderLoanLoad.setPhoneNum(string[17]);
        //风险等级
        ckOrderLoanLoad.setRiskLevel(string[18]);
        //客户群细分
        ckOrderLoanLoad.setCustomerLabel(string[19]);
        //话术模板
        ckOrderLoanLoad.setScriptTemplate(string[20]);
        //还款账号
        ckOrderLoanLoad.setRepaymentNum(string[21]);
        //催收优先级
        ckOrderLoanLoad.setCollectionPriority(string[22]);
        //是否首期
        if (StringUtils.isNotEmpty(string[23])) {
            ckOrderLoanLoad.setIsFirstIssue(Byte.parseByte(string[23]));
        } else {
            ckOrderLoanLoad.setIsFirstIssue(null);
        }
        //新老网贷
        if (StringUtils.isNotEmpty(string[24])) {
            ckOrderLoanLoad.setNewAndOldLoansn(Byte.parseByte(string[24]));
        } else {
            ckOrderLoanLoad.setNewAndOldLoansn(null);
        }
        //退罚息
        ckOrderLoanLoad.setInterestRefund(string[25]);
        //评分
        if (StringUtils.isNotEmpty(string[26])) {
            ckOrderLoanLoad.setScore(Integer.parseInt(string[26]));
        } else {
            ckOrderLoanLoad.setScore(null);
        }
        //状态
        if (StringUtils.isNotEmpty(string[27])) {
            ckOrderLoanLoad.setState(Byte.parseByte(string[27]));
        } else {
            ckOrderLoanLoad.setState(null);
        }
        //还款金额
        ckOrderLoanLoad.setRepaymentAmount(string[28]);
        //还款时间
        ckOrderLoanLoad.setRepaymentDate(string[29]);
        ckOrderLoanLoad.setDataTime(simpleDateFormat1.format(date));
        return ckOrderLoanLoad;
    }

    *//**
     * 读取csv文件
     *
     * @param nFileName
     * @return
     * @throws Exception
     *//*
    private List<String[]> readCsv(String nFileName) throws Exception {
        List<String[]> csvList = new ArrayList<>();
        CsvReader csvReader = new CsvReader(nFileName, ',', Charset.forName("UTF-8"));
        while (csvReader.readRecord()) {
            csvList.add(csvReader.getValues());
        }
        csvReader.close();
        return csvList;
    }*/
}
